#include "key.h"
#include "main.h"

// 按键初始化
void KEY_Init(void) {
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    
    __HAL_RCC_GPIOA_CLK_ENABLE();
    
    GPIO_InitStruct.Pin = KEY1_PIN | KEY2_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(KEY_GPIO_PORT, &GPIO_InitStruct);
		
		//外接卫东按键初始化
		KEYMicro_CLK_EN();
		GPIO_InitStruct.Pin = KEY_MICRO_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(KEY_MICRO_PORT, &GPIO_InitStruct);
		
}

// 获取按键状态(带消抖)
		Key_State KEY_GetState(uint16_t key_pin) {
    static uint32_t last_time[3] = {0};
    static Key_State last_state[3] = {KEY_RELEASED};
    uint8_t idx = (key_pin == KEY_MICRO_PIN) ? 0 : 
                 (key_pin == KEY1_PIN) ? 1 : 2;
    
    uint32_t current_time = HAL_GetTick();
		Key_State current_state =KEY_RELEASED;
		if(idx==0)
    {
			current_state = (HAL_GPIO_ReadPin(KEY_MICRO_PORT, KEY_MICRO_PIN) == GPIO_PIN_RESET) ? 
                              KEY_PRESSED : KEY_RELEASED;
		}
		else 
		{
				current_state = (HAL_GPIO_ReadPin(KEY_GPIO_PORT, key_pin) == GPIO_PIN_RESET) ? 
                              KEY_PRESSED : KEY_RELEASED;
		}
    
    // 状态发生变化时，更新时间和状态
    if (current_state != last_state[idx]) {
        if (current_time - last_time[idx] > KEY_DEBOUNCE_TIME) {
            last_time[idx] = current_time;
            last_state[idx] = current_state;
        }
    }
    
    return last_state[idx];
}
